﻿/// <reference path="ParsedRoute.js" />
/// <reference path="Route.js" />
/// <reference path="HttpRequest.js" />
/// <reference path="../utilities/Xpcom.js" />
///--------------------------------------------------------------------
/// <file name="RouteRepository.js">
///   Delegates HTTP requests to various routes depending on their route patterns.
/// </file>
///--------------------------------------------------------------------

NAMFox.ns(function() { with (NAMFox) {

this.RouteRepository = function() {
    /// <summary>Initializes a new instance of the RoutingHandler class.</summary>
    
    this._routeCollection = [];
};

RouteRepository.prototype = {
    addRoute: function(route) {
        /// <summary>Adds a new route to be handled.</summary>
        /// <param name="route" type="Route">The route to add.</param>
        
        if (!route) {
            throw new Error("Route must not be null.");
        }
        this._routeCollection.push(route);
    },
    
    handleRequest: function(htmlDocument) {
        /// <summary>Handles a request by delegating it to certain routes that match the pattern of the URI.</summary>
        /// <param name="htmlDocument" domElement="true">The HTML document representing the page that was requested.</param>
        
        var uri = htmlDocument.location.href;
        var requestPath = uri.replace(/^http:\/\/(.*)$/, "$1");
        
        this._routeCollection.sort(function(left, right) { return left.getPriority() - right.getPriority(); });

        for (var i = 0; i < this._routeCollection.length; ++i) {
            var routeData = this._routeCollection[i].getRouteData(requestPath);
            
            if (routeData) {
                $.info("URL '" + uri + "' matched '" + routeData.requestHandler.name + "' with priority '" + routeData.requestHandler.priority + "'.");
                
                if ($.trace.traceLevel >= $.traceLevels.TraceVerbose) {
                    for (var j in routeData.values) {
                        if (routeData.values.hasOwnProperty(j)) {
                            $.verbose("  Route Data. " + j + " : " + routeData.values[j]);
                        }
                    }
                }
            
                routeData.requestHandler.handleRequest(new HttpRequest(htmlDocument, routeData.values));
            }
        }
    }
};

}});